// import theme from './content-theme-mark'
// export default theme()
import fs from 'fs'
import path from 'path'
import defu from 'defu'

// https://nuxtjs.org/api/configuration-server/#example-using-https-configuration
const sslKeyPath = '/etc/ssl/2_nanchuan.site.key'
const sslCertPath = '/etc/ssl/1_nanchuan.site_bundle.crt'
const server = {
  port: 3000,
  host: 'localhost',
}
const scripts = []
const scriptBaiduStat = {
  src: 'https://hm.baidu.com/hm.js?5842efcf31735c615e96b30b69824d9e',
}

if (process.env.NODE_ENV !== 'development') {
  server['https'] = {
    cert: fs.readFileSync(sslCertPath),
    key: fs.readFileSync(sslKeyPath),
  }
  scripts.push(scriptBaiduStat)
}

const defaultConfig = {
  server: server,
  build: {
    // 提供一些分析功能，仅在开发时使用
    analyze: true,
    // 重要，通过此配置`babel`可显著减小最终打包体积
    babel: {
      plugins: [
        [
          'component',
          {
            libraryName: 'element-ui',
            styleLibraryName: 'theme-chalk',
          },
        ],
      ],
    },
  },

  /*
   ** Nuxt rendering mode
   ** See https://nuxtjs.org/api/configuration-mode
   */
  mode: 'universal',
  /*
   ** Nuxt target
   ** See https://nuxtjs.org/api/configuration-target
   */
  target: 'server',

  // target: 'static',
  ssr: true,

  // 设定程序的源路径，会影响相对路径的行为
  srcDir: __dirname,

  //    ** Build configuration  # TODO
  //    ** See https://nuxtjs.org/api/configuration-build/
  transpile: [
    __dirname, // transpile node_modules/@nuxt/content-theme-docs
  ],

  // [nuxt + tailwind + element-ui 踩了一个生成 css 的坑 - 知乎](https://zhuanlan.zhihu.com/p/91463119)
  // purgeCSS: {
  //   enabled: false,
  // },

  // 是否自动注入全局组件
  // See https://nuxtjs.org/api/configuration-components
  components: true,

  //    ** See https://nuxtjs.org/api/configuration-head
  head: {
    title: process.env.npm_package_author_name || '南川笔记',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content:
          process.env.npm_package_description || '南川笔记——致力于知识服务',
      },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
    script: scripts,
  },

  //    Nuxt.js dev-modules
  buildModules: [
    // css底层框架，本项目高度依赖于此
    '@nuxtjs/tailwindcss',

    // 颜色切换与SVG导入
    // https://nuxtjs.org/blog/going-dark-with-nuxtjs-color-mode
    '@nuxtjs/svg',
    '@nuxtjs/color-mode',

    '@nuxtjs/pwa',
    '@nuxtjs/google-fonts',

    /// 用于代码检查
    '@nuxtjs/eslint-module',

    // 用于配合使用stylus等postcss
    '@nuxtjs/style-resources',
  ],

  // Nuxt.js modules
  modules: [
    // 用于国际化
    'nuxt-i18n',

    // 用于博客内容服务
    '@nuxt/content',

    // 用于网络请求
    '@nuxtjs/axios',

    // 用于统一cookie
    'cookie-universal-nuxt',
  ],

  //    ** Plugins to load before mounting the App
  //    ** https://nuxtjs.org/guide/plugins
  plugins: [
    // 状态树相关（包括导航栏的数据等）
    '~/plugins/init-store',

    // 网络相关
    '~/plugins/api',
    // 依赖axios
    '~/plugins/axios',

    // 依赖ali-oss，已从前端依赖转移到后端，以减少前端体积
    '~/plugins/ali-OSS-put',

    // 本来想尝试注册全局login组件，但由于它依赖于其他全局组件，因此未能实现
    // { src: '~/plugins/login', mode: 'client' },

    // 文档相关
    '~/plugins/markdown',

    // 组件相关
    // 依赖element-ui
    '~/plugins/element-ui',

    // 依赖vue-scrollactive
    '~/plugins/vue-scrollactive',

    '~/plugins/comments',

    '~/plugins/control',

    // '~/plugins/nuxt-client-init.client',

    // { src: '~/plugins/g6', ssr: false },

    // { src: '~plugins/echarts' },
  ],

  //    ** Axios module configuration
  //    ** See https://axios.nuxtjs.org/options
  axios: {},
  compilerOptions: {
    types: ['@nuxt/types', '@nuxtjs/axios'],
  },

  //    ** Content module configuration
  //    ** See https://content.nuxtjs.org/configuration
  router: {
    // default: history, 不要修改，除非服务器已经配置对应路由
    mode: 'history',
    base: '/',
    extendRoutes(routes, resolve) {
      routes.push({
        name: 'home',
        path: '/',
        redirect: '/about/me/home',
      })
    },
  },
  content: {
    markdown: {
      prism: {
        theme: 'prism-themes/themes/prism-material-oceanic.css',
      },
    },

    dir: 'content', // default
    apiPrefix: 'content-api', // default: '_content'
    liveEdit: true, // 在线编辑黑魔法（不过有一定bug）
  },

  generate: {
    fallback: '404.html',
    routes: ['/'],
  },

  googleFonts: {
    families: {
      'DM+Sans': true,
      'DM+Mono': true,
    },
  },

  tailwindcss: {
    // cssPath: '~/assets/css/tailwind.css',
    configPath: 'tailwind.config.js',
    // 以下写法和上面等价，具体见 https://tailwindcss.nuxtjs.org/options
    // config: require('./tailwind.config'),
    exposeConfig: false,
  },

  // 全局css
  css: [
    '~/assets/css/global_base.css',
    // '~assets/css/nuxt-content-theme.less',
    '~/assets/css/nuxt_content_enhance.less',
    '~/assets/css/tailwindcss/custom_color_mode.less',

    // 如果在 create-nuxt-app 中默认选了 Element-UI 的，还需要将 Element-UI 的全局样式去掉
    // 'element-ui/lib/theme-chalk/index.css',
  ],

  // https://i18n.nuxtjs.org/
  i18n: {
    locales: [
      {
        code: 'en',
        iso: 'en-US',
        file: 'en-US.js',
        name: 'English',
      },
      {
        code: 'zh',
        iso: 'zh-CN',
        file: 'zh-CN.js',
        name: '简体中文',
      },
    ],
    // https://i18n.nuxtjs.org/routing.html#strategy
    strategy: 'prefix_and_default',
    defaultLocale: 'zh',
    parsePages: false,
    lazy: true,
    seo: false,
    langDir: 'langs/',
    vueI18n: {
      fallbackLocale: 'zh',
    },
    detectBrowserLanguage: {
      useCookie: true,
      cookieKey: 'i18n_redirected',
    },
  },
  // https://pwa.nuxtjs.org/icon
  pwa: {},
  hooks: {},
}

export default (userConfig) => {
  const md5 = require('./plugins/md5').md5
  const config = defu.arrayFn(userConfig, defaultConfig)

  config.hooks['content:file:beforeInsert'] = (document) => {
    document.scopePath = '/' + document.dir.split('/')[2]

    document.uniDirPath = '/' + document.dir.split('/').slice(2).join('/')

    document.uniPath = '/' + document.path.split('/').slice(2).join('/')

    document.title = document.title || document.slug

    document.menuTitle = document.menuTitle || document.title

    document.author = document.author || process.env.npm_package_author_name

    document.fullScreen = document.fullScreen || false

    document.id = document.id || md5(document.title)
  }

  return config
}
